<?php


namespace App\Controller\Admin;

use App\Controller\BaseController;
use App\Helpers\Utils;
use App\Model\AdminHasPermission;
use App\Model\AdminPermission;
use App\Model\AdminUser;
use App\Request\Admin\AdminUserRequest;
use App\Service\Admin\AuthService;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\RefreshTokenMiddleware;

/**
 * @AutoController()
 * @Middleware(RefreshTokenMiddleware::class)
 */
class AdministratorsController extends BaseController
{
    public function lists()
    {
        $request = $this->request;

        $data = AdminUser::where(function ($query)use ($request){
            if ($request->has('username')){
                $query->where('username',$request->username);
            }

        })->paginate($request->limit);

        return $this->success(['items' => $data->items(),'total' => $data->total()]);
    }


    public function store(AdminUserRequest $request)
    {
        AdminUser::create($request->inputs(['username','password']));

        return  $this->message('添加管理员成功');
    }


    public function update(AdminUserRequest $request)
    {
        $post = $request->validated();
        $post['password'] = Utils::password($post['password']);

        AdminUser::where('id',$this->request->input('id'))->update($post);

        return  $this->message('编辑管理员成功');
    }

    public function destroy()
    {
        AdminUser::where('id',$this->request->input('id'))->delete();
        return  $this->message('删除管理员成功');
    }



    public function getPermission()
    {
        $user = AdminUser::find($this->request->input('id'));

        return $this->success( (new AuthService)->allPermission($user));
    }

    public function setPermission()
    {
        $user_id = $this->request->input('id');
        AdminHasPermission::where('admin_id',$user_id)->delete();


        //  写入权限
        foreach ($this->request->input('ids') as $k => $v){

            $find = AdminPermission::where('id',$v)->first();

            $cc = AdminHasPermission::where('admin_id',$user_id)->where('permission_id',$find->id)->count();
            while ($find && empty( $cc) ){

                AdminHasPermission::create([
                    'admin_id'  =>  $user_id,
                    'permission_id' =>  $find->id
                ]);

                $find = AdminPermission::where('id',$find->pid)->first();
            }
        }


        $user = AdminUser::find($user_id);

        $user->update(['permissions' => Utils::ArraytoJson($this->request->input('ids'))]);
        return $this->message('设置管理员权限成功');
    }
}
